package co.legu.carpool.api.order.controller;

import co.legu.carpool.api.order.entity.WorkOrder;
import co.legu.carpool.api.order.service.IWorkOrderService;
import co.legu.carpool.api.order.vo.AddWorkOrderVO;
import co.legu.carpool.api.route.entity.Route;
import co.legu.carpool.api.route.service.IRouteService;
import co.legu.carpool.api.wechat.util.WechatSession;
import co.legu.carpool.common.annotation.AdminOnly;
import co.legu.carpool.common.bean.IdVO;
import co.legu.modules.common.bean.Result;
import co.legu.modules.common.util.Strings;
import co.legu.modules.pager.annotation.Pager;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * <p>
 * 工单 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/api/order")
public class WorkOrderController {
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private IRouteService routeService;


    /**
     * @api {post} /api/order/add 工单 - 添加工单
     * @apiDescription 添加工单
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiParam {String} routeId 路线ID*
     * @apiParam {DirectionType} direction 方向*
     * @apiParam {String} direction.DirectionType.STARTOEND 起点去终点
     * @apiParam {String} direction.DirectionType.ENDTOSTART 终点去起点
     * @apiParam {EntityType} entity 人或者车*
     * @apiParam {String} entity.EntityType.PEOPLE 人
     * @apiParam {String} entity.EntityType.CAR 车
     * @apiParam {String} phone 手机号*
     * @apiParam {String} departureTime 出发时间yyyy-MM-dd HH:mm:ss*
     * @apiParam {String} seatNumber 车辆座位or坐车人数
     * @apiParam {String} remarks 描述
     * @apiParam {String} startRemarks 起点描述
     * @apiParam {String} endRemarks 终点描述
     * @apiSuccess {data} object 通用返回值
     */
    @PostMapping("/add")
    public Result<?> add(@RequestBody @Valid AddWorkOrderVO add) {
        // 添加前的校验
        var routeCount = routeService.lambdaQuery().eq(Route::getId, add.getRouteId()).count();
        if (routeCount <= 0) return Result.fail("没有当前路线");

        // 默认值添加
        var workOrder = new WorkOrder();
        BeanUtils.copyProperties(add, workOrder);
        workOrder.setId(IdWorker.getIdStr());
        workOrder.setOpenId(WechatSession.openid());
        workOrder.setAddTime(LocalDateTime.now());
        workOrder.setDeleted(false);
        // 添加数据
        boolean addResult = workOrderService.save(workOrder);
        return Result.auto(addResult);
    }


    /**
     * @api {post} /api/order/delete 工单 - 删除工单 - 管理员
     * @apiDescription 管理员使用
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiParam {String} id 工单ID*
     * @apiSuccess {data} object 通用返回值
     */
    @AdminOnly
    @PostMapping("/delete")
    public Result<?> delete(@RequestBody @Valid IdVO idVO) {
        // 删除数据
        boolean delResult = workOrderService.lambdaUpdate()
                .set(WorkOrder::getDeleted, true)
                .eq(WorkOrder::getId, idVO.getId())
                .update();
        return Result.auto(delResult);
    }

    /**
     * @api {post} /api/order/deleteByUser 工单 - 删除工单
     * @apiDescription 用户使用，只能删除自己发布的工单
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiParam {String} id 工单ID*
     * @apiSuccess {data} object 通用返回值
     */
    @PostMapping("/deleteByUser")
    public Result<?> deleteByUser(@RequestBody @Valid IdVO idVO) {
        var order = workOrderService.getById(idVO.getId());
        if (order == null) return Result.fail("没有当前工单");
        if (!WechatSession.openid().equals(order.getOpenId())) return Result.fail("不可以删除其他用户的工单");

        // 删除数据
        boolean delResult = workOrderService.lambdaUpdate()
                .set(WorkOrder::getDeleted, true)
                .eq(WorkOrder::getId, idVO.getId())
                .update();
        return Result.auto(delResult);
    }

    /**
     * @api {get} /api/order/infoList 工单 - 已发布的工单分页
     * @apiDescription 查询工单
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiSuccess {DirectionType} direction 方向*
     * @apiSuccess {String} direction.STARTOEND 起点去终点
     * @apiSuccess {String} direction.ENDTOSTART 终点去起点
     * @apiSuccess {EntityType} entity 人或者车*
     * @apiSuccess {String} entity.PEOPLE 人
     * @apiSuccess {String} entity.CAR 车
     * @apiSuccess {String} phone 手机号*
     * @apiSuccess {String} departureTime 出发时间yyyy-MM-dd HH:mm:ss*
     * @apiSuccess {String} seatNumber 车辆座位or坐车人数
     * @apiSuccess {String} remarks 描述
     * @apiSuccess {String} startRemarks 起点描述
     * @apiSuccess {String} endRemarks 终点描述
     * @apiSuccess {Boolean} deleted 是否删除
     */
    @GetMapping("/infoList")
    public Result<?> info(String id) {
        var wrapper = Wrappers.<WorkOrder>lambdaQuery()
                .orderByAsc(WorkOrder::getDepartureTime)
                .eq(WorkOrder::getOpenId, WechatSession.openid());
        //查询数据
        var list = workOrderService.lambdaQuery().list();
        return Result.success(list);
    }

    /**
     * @api {get} /api/order/list 工单 - 查询工单分页
     * @apiDescription 查询工单
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiParam {String} routeId 路线ID*
     * @apiParam {DirectionType} direction 方向*
     * @apiParam {String} direction.DirectionType.STARTOEND 起点去终点
     * @apiParam {String} direction.DirectionType.ENDTOSTART 终点去起点
     * @apiParam {EntityType} entity 人或者车*
     * @apiParam {String} entity.EntityType.PEOPLE 人
     * @apiParam {String} entity.EntityType.CAR 车
     * @apiParam {String} departureTime 出发时间yyyy-MM-dd*
     * @apiParam {String} openId 用户唯一标识
     * @apiSuccess {DirectionType} direction 方向*
     * @apiSuccess {String} direction.STARTOEND 起点去终点
     * @apiSuccess {String} direction.ENDTOSTART 终点去起点
     * @apiSuccess {EntityType} entity 人或者车*
     * @apiSuccess {String} entity.PEOPLE 人
     * @apiSuccess {String} entity.CAR 车
     * @apiSuccess {String} phone 手机号*
     * @apiSuccess {String} departureTime 出发时间yyyy-MM-dd HH:mm:ss*
     * @apiSuccess {String} seatNumber 车辆座位or坐车人数
     * @apiSuccess {String} remarks 描述
     * @apiSuccess {String} startRemarks 起点描述
     * @apiSuccess {String} endRemarks 终点描述
     */
    @Pager
    @GetMapping("/list")
    public Result<?> list(String routeId,
                          String direction,
                          String entity,
                          String openId,
                          @RequestParam(name = "departureTime", required = false)
                          @DateTimeFormat(pattern = "yyyy-MM-dd")
                          LocalDate departureTime) {
        var wrapper = Wrappers.<WorkOrder>lambdaQuery()
                .eq(WorkOrder::getDeleted, false)
                .orderByAsc(WorkOrder::getDepartureTime);

        if (Strings.notBlank(routeId)) wrapper.eq(WorkOrder::getRouteId, routeId);

        if (Strings.notBlank(direction)) wrapper.eq(WorkOrder::getDirection, direction);

        if (Strings.notBlank(entity)) wrapper.eq(WorkOrder::getEntity, entity);

        if (Strings.notBlank(openId)) wrapper.eq(WorkOrder::getOpenId, openId);

        // 默认时间大于当天00:00:00
        if (departureTime != null){
            wrapper.ge(WorkOrder::getDepartureTime, LocalDateTime.of(departureTime, LocalTime.MIN));
            wrapper.le(WorkOrder::getDepartureTime, LocalDateTime.of(departureTime, LocalTime.MAX));
        }else {
            wrapper.ge(WorkOrder::getDepartureTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        }

        //查询数据
        var list = workOrderService.list(wrapper);
        return Result.success(list);
    }

}

